package com.yinhe.music.yhmusic.utils;

import com.apkfuns.logutils.LogUtils;
import com.hwangjr.rxbus.RxBus;
import com.yinhe.music.event.RxBusEventType;
import com.yinhe.music.yhmusic.db.DataBaseAccessor;
import com.yinhe.music.yhmusic.db.bean.MenuDBEntity;
import com.yinhe.music.yhmusic.db.bean.SongDBEntity;
import com.yinhe.music.yhmusic.model.Music;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by 何晓华 on 2017/9/30.
 */

public class SongUtil {
    public static List<Integer> getSongIdList(String songs) {
        List<Integer> list = new ArrayList<>();
        try {
            if (songs != null) {
                if (songs.contains(",")) {
                    String[] songids = songs.split(",");
                    for (String songid : songids) {
                        if (!songid.isEmpty()) {
                            list.add(Integer.parseInt(songid));
                        }
                    }
                } else if (songs.length() > 0) {
                    list.add(Integer.parseInt(songs));
                }
            }
        } catch (Exception e) {
            LogUtils.e(e);
        }
        return list;
    }

    public static void removeSong(int songId, int menuId) {
        MenuDBEntity menuDBEntity = DataBaseAccessor.getInstance().getMenuByIdSyn(menuId);
        if (menuDBEntity != null) {
            List<Integer> idList = SongUtil.getSongIdList(menuDBEntity.getSongIds());
            if (idList.contains(songId)) {
                String newSongIds = menuDBEntity.getSongIds().replace(songId + ",", "");
                if (newSongIds.contains(String.valueOf(songId))) {
                    newSongIds = menuDBEntity.getSongIds().replace(String.valueOf(songId), "");
                }
                menuDBEntity.setSongIds(newSongIds);
                if (menuDBEntity.getSongnum() > 0) {
                    menuDBEntity.setSongnum(menuDBEntity.getSongnum() - 1);
                }
            }
            RxBus.get().post(RxBusEventType.SongMenu.DELETE_MENU_LOCAL_MUSIC, (Integer) songId);
            DataBaseAccessor.getInstance().updateMenu(menuDBEntity);
        }
    }

    /**
     * 保存本地歌曲到数据库
     *
     * @param musicList 要保存的歌曲
     */
    public static void saveSong(List<Music> musicList) {
        List<SongDBEntity> songDBEntityList = new ArrayList<>();
        if (musicList != null) {
            for (Music music : musicList) {
                SongDBEntity songDBEntity = new SongDBEntity(music);
                songDBEntity.setSyn(true);
                songDBEntity.setSysmusiclang(-1);
                songDBEntityList.add(songDBEntity);
            }
            LogUtils.i("saveSong:" + songDBEntityList.size());
            DataBaseAccessor.getInstance().insertSongList(songDBEntityList);
        }
    }
}
